package com.support.observer;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.apache.commons.lang.StringUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Service;


@SuppressWarnings("serial")
public class ReloadCacheEvent extends ApplicationEvent
{
	private Object service;
	private String methodName;
	private Object[] params;

	// 存放构造器送入的值
	// private String serviceId;
	// 构造器参数可以随意设置，这里为了方便调试，设置为字符串
	public ReloadCacheEvent(Object service, String methodName, Object... args)
	{
		super(service);
		this.service = service;
		this.methodName = methodName;
		this.params = args;
	}

	// 自定义一个方法，这个方法也可以随意写，这里也是测试用
	public void reloadCahce(ApplicationContext context)
	{
		try
		{
			Class<?> targetClass = service.getClass();
			
			if(!AopUtils.isAopProxy(service))
			{
//				targetClass = AopUtils.getTargetClass(service);
//				((Service)targetClass.getAnnotation(Service.class)).value();
				String serviceName = targetClass.getAnnotation(Service.class).value();
				
				if(StringUtils.isEmpty(serviceName))
				{
					String className = targetClass.getName().substring(targetClass.getName().lastIndexOf('.') + 1);
					serviceName = className.substring(0, 1).toLowerCase() + className.substring(1);
				}
				
				service = context.getBean(serviceName);
			}
			
			if (methodName == null)
			{
				methodName = "reloadCache";
			}
			
			Method method = service.getClass().getMethod(methodName);
			
			if ("void".equals(method.getReturnType().getName()) && 0 == method.getParameterTypes().length)
			{
				method.invoke(service, new Object[] {});
			}
			else if(method.getParameterTypes().length > 0)
			{
				method.invoke(service, params);
			}

			System.out.println("getAnnotation:" + method.getAnnotations());
			System.out.println("调用get方法：" + method.invoke(service));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		System.out.println("********My event**************");
		System.out.println(service.getClass().getName());
		System.out.println("*******************************");
	}
}